import { provide, reactive, inject, nextTick } from 'vue'
import _ from "lodash"

class LyFocus {
  constructor() {
    this.state = reactive({
      keyValue: "",
      focusId: "",
      widgetList: [],
      scrollList: [],
      popupList: [],
      keyboard: {}
    })
    provide('xmfocus', this.state)
  }
  state

  focusChange(ev) {
    const _state = this.state
    if (_state.focusId === ev) return
    _state.focusId = ev
  }
  keyboardChange(ev) {
    const _state = this.state
    _state.keyboard = ev
  }
  keyValueChange(ev) {
    const _state = this.state
    _state.keyValue = ev
  }
}


export function feInject() {
  const state = inject('xmfocus')
  return {
    state,
    focusChange(ev) {
      if (state.focusId === ev) return
      nextTick(() => {
        state.focusId = ev
      })
    },
    widgetCreate(widget) {
      const _list = [...state.widgetList];
      const _index = _.findIndex(_list, function (v) { return v.uid === widget.uid });
      if (_index > -1) {
        _list[_index] = widget
      } else {
        _list.push(widget);
      }
      state.widgetList = _list
    },
    widgetDelete(widget) {
      const _list = [...state.widgetList];
      const _index = _.findIndex(_list, function (v) { return v.uid === widget.uid });
      if (_index > -1) {
        _list.splice(_index, 1);
        state.widgetList = _list
      }
    },
    scrollCreate(widget) {
      const _list = [...state.scrollList];
      const _index = _.findIndex(_list, function (v) { return v.uid === widget.uid });
      if (_index > -1) {
        _list[_index] = widget
      } else {
        _list.push(widget);
      }
      state.scrollList = _list
    },
    scrollDelete(widget) {
      const _list = [...state.scrollList];
      const _index = _.findIndex(_list, function (v) { return v.uid === widget.uid });
      if (_index > -1) {
        _list.splice(_index, 1);
        state.scrollList = _list
      }
    },
    popupCreate(widget) {
      const _list = [...state.popupList];
      const _index = _.findIndex(_list, function (v) { return v.uid === widget.uid });
      if (_index > -1) {
        _list.splice(_index, 1);
        _list.push(widget);
      } else {
        _list.push(widget);
      }
      state.popupList = _list
    },
    popupDelete(widget) {
      const _list = [...state.popupList];
      const _index = _.findIndex(_list, function (v) { return v.uid === widget.uid });
      if (_index > -1) {
        _list.splice(_index, 1);
        state.popupList = _list
      }
    },
  }
}
